package org.saxonextensions.eml.emitter;

import net.sf.saxon.trans.XPathException;
import net.sf.saxon.event.StandardOutputResolver;

import javax.xml.transform.Result;
import java.net.URI;
import java.net.URISyntaxException;

/**
 * Extended aoutput resolver that handle dev://null URI
 *
 * @author Ivan Latysh <ivan@yourmail.com>
 * @version 0.1
 * @since 16-Mar-2009 5:32:37 PM
 */
public class ExtendedlOutputResolver extends StandardOutputResolver {

  /** Shared null result */
  private final DevNullResult result = new DevNullResult();

  @Override
  public Result resolve(String href, String base) throws XPathException {

    try {
      URI absoluteURI = null;
      if (href.length() == 0) {
          if (base==null) {
              throw new XPathException("The system identifier of the principal output file is unknown");
          }
          absoluteURI= new URI(base);
      } else {
          absoluteURI= new URI(href);
      }
      // if it is a dev://null scheme, return custom result
      if ("dev".equals(absoluteURI.getScheme()) && "null".equals(absoluteURI.getHost())) {
        return result;
      }
    } catch (URISyntaxException e) {
      throw new XPathException("Invalid URI. {href="+href+"} {base="+base+"}", e);
    }

    return super.resolve(href, base);
  }
}